package main

import (
	"fmt"
	"log"
	"os"

	rice "github.com/GeertJohan/go.rice"

	"io/ioutil"

	"golang.org/x/sys/windows/registry"
)

var logger *log.Logger

func init() {
	logFile, err := os.OpenFile("installLog.txt", os.O_RDWR|os.O_CREATE, 0777)
	if err != nil {
		fmt.Printf("open file error=%s\r\n", err.Error())
		os.Exit(-1)
	}

	// defer logFile.Close()
	//logger:=log.New(logFile,"\r\n", log.Ldate | log.Ltime | log.Llongfile)
	logger = log.New(logFile, "\r\n", log.Ldate|log.Ltime|log.Lshortfile)
}
func regKey(path string) error {
	vconsoleKey, ok, err := registry.CreateKey(registry.CLASSES_ROOT, `ceeloConsole`, registry.CREATE_SUB_KEY|registry.SET_VALUE)
	if err != nil {
		logger.Printf("CreateKey console err :%v\n", err)
		return err
	}
	if ok {
		return err
	}
	defer vconsoleKey.Close()
	vconsoleKey.SetStringValue("URL Protocol", "")
	// 要检测执行文件当前目录
	vconsoleKey.SetStringValue("DefaultIcon", path)
	shellKey, _, err := registry.CreateKey(vconsoleKey, `shell`, registry.CREATE_SUB_KEY)
	if err != nil {
		logger.Printf("CreateKey shell err :%v\n", err)
		return err
	}
	openKey, _, err := registry.CreateKey(shellKey, `open`, registry.CREATE_SUB_KEY)
	if err != nil {
		logger.Printf("CreateKey open err :%v\n", err)
		return err
	}
	commandKey, _, err := registry.CreateKey(openKey, `command`, registry.CREATE_SUB_KEY|registry.SET_VALUE)
	if err != nil {
		logger.Printf("CreateKey err :%v\n", err)
		return err
	}
	commandKey.SetStringValue("", path)

	return nil
}

func main() {
	logger.Printf("Start:\n")
	box, err := rice.FindBox("./dir")
	if err != nil {
		logger.Printf("Asset was not found.\n")
		return
	}
	logger.Printf("Asset Finding Complete!\n")
	str, err := box.String("httpServer.exe")
	if err != nil {
		println(err.Error())
		return
	}
	path := `C:\ceelo`
	name := path + `\` + `ceeloConsole.exe`
	logger.Printf("RegKey begin\n")
	regKey(name)
	logger.Printf("ReKey Over!\n")
	err = os.Mkdir(path, 0777)
	if err != nil {
		logger.Println("create dir", err.Error())
		return
	}
	logger.Printf("Create Dir OK!\n")
	err = ioutil.WriteFile(name, []byte(str), 0777)
	if err != nil {
		println(err.Error())
		return
	}
	logger.Printf("Install Over!\n")
}
